//
//  RCacheListViewController.m
//  iPlan
//
//  Created by 侯伟 on 2021/8/27.
//

#import "RCacheListViewController.h"
#import "RSRefreshTableView.h"
#import "RCacheTableViewCell.h"

#import "RCacheCellObj.h"
#import "RVideoPlayerViewController.h"

#import "RCacheManager.h"

@interface RCacheListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) MyLinearLayout *contentLayout;
/// 列表
@property(nonatomic,strong) UITableView* tableView;
//底部
@property(nonatomic,strong) MyLinearLayout *bottomLayout;
//编辑
@property(nonatomic,strong) UIButton* editBtn;
//所有的
@property(nonatomic,strong) UIButton* allBtn;
//删除
@property(nonatomic,strong) UIButton* delBtn;

@property (nonatomic, strong)NSArray<RCacheCellObj *> *datas;

@end

@implementation RCacheListViewController

- (BOOL)isEditing{
    return self.editBtn.selected;
}

- (void)loadView{
    [super loadView];
    self.view.backgroundColor = UIColor.whiteColor;
    
    // 线性布局
    MyLinearLayout *contentLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    contentLayout.myMargin = 0;
    [self.view addSubview:contentLayout];
    _contentLayout = contentLayout;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupNavBar];
    
    [self setupViews];
    
    [self reloadData];
}

- (void)setupNavBar{
    self.navigationItem.title = @"我的缓存";
    
    UIButton* editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [editBtn setTitle:@"取消" forState:UIControlStateSelected];
    [editBtn setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
    [editBtn addTarget:self action:@selector(editClicked:) forControlEvents:UIControlEventTouchUpInside];
    editBtn.titleLabel.font = FONTMID(15);
    editBtn.myHeight = PX(44);
    editBtn.myWidth = PX(44);
    _editBtn = editBtn;
    UIBarButtonItem* editItem = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
    self.navigationItem.rightBarButtonItem = editItem;
}

-(void)setupViews{
    
    //列表
    UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [tableView registerClass:NSClassFromString(cacheCell) forCellReuseIdentifier:cacheCell];
    tableView.tableFooterView = [UIView new];
    tableView.backgroundColor = UIColor.whiteColor;
    tableView.myMargin = 0;
    tableView.weight = 1.0;
    [self.contentLayout addSubview:tableView];
    _tableView = tableView;
    
    MyLinearLayout* bottomLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
    bottomLayout.padding = UIEdgeInsetsMake(8, 16, isIphoneX?IPHONE_BOTTOM_SAFEINSET:8, 16);
    bottomLayout.myHeight = IPHONE_TAB_BAR_HEIGHT;
    bottomLayout.gravity = MyGravity_Horz_Fill;
    bottomLayout.myMargin = 0;
    [self.contentLayout addSubview:bottomLayout];
    _bottomLayout = bottomLayout;
    
    UIButton* allBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [allBtn setTitle:@"全选" forState:UIControlStateNormal];
    [allBtn setImage:[UIImage imageNamed:@"common_select_n"] forState:UIControlStateNormal];
    [allBtn setImage:[UIImage imageNamed:@"common_select_h"] forState:UIControlStateSelected];
    [allBtn setTitleColor:COLOR_GRAY_BASE forState:UIControlStateNormal];
    allBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 4);
    allBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 0);
    allBtn.titleLabel.font = FONT_FIT(15);
    [allBtn addTarget:self action:@selector(allSelectClicked:) forControlEvents:UIControlEventTouchUpInside];
    allBtn.myMargin = 0;
    [allBtn sizeToFit];
    [bottomLayout addSubview:allBtn];
    _allBtn = allBtn;
    
    UIButton* delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
    [delBtn setTitleColor:COLOR_RED forState:UIControlStateNormal];
    delBtn.titleLabel.font = FONT_FIT(15);
    [delBtn addTarget:self action:@selector(deleteClicked:) forControlEvents:UIControlEventTouchUpInside];
    delBtn.myMargin = 0;
    [delBtn sizeToFit];
    [bottomLayout addSubview:delBtn];
    _delBtn = delBtn;
    
    self.bottomLayout.visibility = MyVisibility_Gone;

}

#pragma mark -- data

- (void)reloadData{
    self.datas = [RCacheManager.share allCacheCells];
    
    [self.tableView reloadData];
}


- (void)pauseResumeOrPlay:(RCacheCellObj *)cacheObj{
    // 这里异步调用, 防止阻塞主线程
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id<MCSAssetExporter> exporter = cacheObj.exporter;
        switch (exporter.status ) {
            case MCSAssetExportStatusUnknown:
            case MCSAssetExportStatusFailed:
            case MCSAssetExportStatusSuspended:
            case MCSAssetExportStatusWaiting:{
                [exporter resume];
            }
                break;
            case MCSAssetExportStatusExporting:{
                [exporter suspend];
            }
                break;
            case MCSAssetExportStatusCancelled:
                break;
            case MCSAssetExportStatusFinished: {
                // 下载完成后, 获取播放地址进行播放
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self playCacheObj:cacheObj.mediaObj];
                });
            }
                break;
        }
    });
}

- (void)playCacheObj:(RCacheObj*)mediaObj{
    
    RVideoPlayerViewController *playerController = [RVideoPlayerViewController new];
    playerController.videoObj = mediaObj;
    
    [self presentViewController:playerController animated:YES completion:nil];
}


#pragma mark -- operations

- (void)editClicked:(UIButton*)sender{
    sender.selected = !sender.selected;
    self.allBtn.selected = NO;
    
    [self.delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
    self.bottomLayout.visibility = sender.selected?MyVisibility_Visible:MyVisibility_Gone;
    
    [self.tableView reloadData];
}

- (void)allSelectClicked:(UIButton*)sender{
    
    sender.selected = !sender.selected;
    
    for (RCacheCellObj* obj in self.datas) {
        obj.mediaObj.isSelected = sender.selected;
    }
    if(sender.selected){
        [self.delBtn setTitle:[NSString stringWithFormat:@"删除(%ld)",self.datas.count] forState:UIControlStateNormal];
    }else{
        [self.delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
    }

    [self.tableView reloadData];
}

- (void)deleteClicked:(UIButton*)sender{
    
    [self editClicked:self.editBtn];
    
    for (RCacheCellObj* obj in self.datas) {
        if(obj.mediaObj.isSelected){
            NSString* urlStr = obj.mediaObj.url;
            [[RCacheManager share] removeCacheWithURLStr:urlStr];
        }
    }
    [self reloadData];
}


- (void)checkSelectState{
    
    NSInteger selectCount = 0;
    for (RCacheCellObj* obj in self.datas) {
        if(obj.mediaObj.isSelected){
            selectCount += 1;
        }
    }
    self.allBtn.selected = selectCount == self.datas.count;
    
    [self.delBtn setTitle:[NSString stringWithFormat:@"删除(%ld)",selectCount] forState:UIControlStateNormal];
}


#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RCacheTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cacheCell forIndexPath:indexPath];
    cell.selectBtn.visibility = [self isEditing] ? MyVisibility_Visible:MyVisibility_Gone;
    if([self isEditing]){
        cell.selectBtn.selected = self.datas[indexPath.row].mediaObj.isSelected;
    }
    WeakSelf
    cell.selectBlock = ^(BOOL Bool) {
        weakSelf.datas[indexPath.row].mediaObj.isSelected = Bool;
        [weakSelf checkSelectState];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(RCacheTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RCacheCellObj* row = self.datas[indexPath.row];
    [row bindCell:cell atIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(RCacheTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    RCacheCellObj* row = self.datas[indexPath.row];
    [row unbindCell:cell atIndexPath:indexPath];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return PX(94) + 32;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    RCacheCellObj *row = self.datas[indexPath.row];
    [self pauseResumeOrPlay:row];
}

@end
